package org.eden.rpc.service.serviceImpl;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import org.eden.rpc.common.entity.dao.User;
import org.eden.rpc.common.service.UserService;
import org.eden.rpc.service.dao.SqlSessionFactoryHolder;
import org.eden.rpc.service.dao.UserMapper;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public User getUserByUsername() {
        User user = new User();
        user.setUsername("zka");
        user.setId(1L);
        return user;
    }

    @Override
    public Long register(User user) {
        LocalDateTime now = LocalDateTime.now();
        user.setRegTime(now);
        user.setValid(true);
        user.setDelete(false);
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        try (SqlSession sqlSession = SqlSessionFactoryHolder.get().openSession(true)){
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.insert(user);
            return user.getId();
        } catch (PersistenceException e) {
            logger.error(e.getMessage());
            return -1L;
        }
    }

    @Override
    public User getById(Long id) {
        try (SqlSession sqlSession = SqlSessionFactoryHolder.get().openSession(true)){
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            return userMapper.getById(id);
        } catch (PersistenceException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public Long login(User user) {
        return null;
    }

}
